﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;
using Ecopsy.DataTier;
using SqlLibrary;
using Ecopsy.Tools;
using System.ComponentModel;

public partial class Ctl_ctlSideShedule : System.Web.UI.UserControl
{

#region Property
    public string KeyPref = "Ctl_ctlSurfaceList";

    public DateTime DtStart
    {
        get { return GetDate(txtDtStart.Text); }
        set
        {
            txtDtStart.Text = value.ToShortDateString();
            (Where.ListLoadStatment as SideListWithContracts.SqlLoadStatment).DtStart = value;
        }
    }

    public DateTime DtEnd
    {
        get { return GetDate(txtDtEnd.Text); }
        set
        {
            txtDtEnd.Text = value.ToShortDateString();
            (Where.ListLoadStatment as SideListWithContracts.SqlLoadStatment).DtFinish = value;
        }
    }

    

    public SideListWithContracts.SqlLoadStatment.Q_Type[] Q_TypeSet
    {
        get
        {
            List<SideListWithContracts.SqlLoadStatment.Q_Type> res = new List<SideListWithContracts.SqlLoadStatment.Q_Type>();
            if (chOnlyFree.Checked)
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OnlyFree);
            if (chOnlyFull.Checked)
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OnlyFull);
            if (chOverFlow_Q.Checked)
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OverFlow_Q);
            if (chSelected.Checked )
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OnlySelected );

            return res.ToArray<SideListWithContracts.SqlLoadStatment.Q_Type>();

        }
        set 
        {
            SideListWithContracts.SqlLoadStatment.Q_Type[] l = value;
            for (int i = 0; i < l.Length; i++)
            {
                switch (l[i])
                { 
                    case SideListWithContracts.SqlLoadStatment.Q_Type .OnlyFull :
                        chOnlyFull.Checked  = true;
                        break ;
                    case SideListWithContracts.SqlLoadStatment.Q_Type .OnlyFree :
                        chOnlyFree.Checked = true;
                        break ;
                    case SideListWithContracts.SqlLoadStatment.Q_Type .OnlySelected  :
                        chSelected.Checked = true;
                        break ;
                    case SideListWithContracts.SqlLoadStatment.Q_Type.OverFlow_Q :
                        chOverFlow_Q .Checked =true ;
                        break;
                }
            }
        }

    }

    private Contract _Contract = null;
    /// <summary>
    /// Контракт отражаемый на расписании 
    /// </summary>    
    public Contract Contract
    {
        get
        {
            return _Contract;
        }
        set { _Contract = value; }
    }

    //public DateTime DtStartOfPeriod
    //{
    //    get
    //    {
    //        DateTime res;
    //        if (DateTime.TryParse(txtDtEnd.Text, out res))
    //            return res;
    //        else
    //            return DateTime.Now;
    //    }
    //    set
    //    {
    //        txtDtEnd.Text = value.ToShortDateString();
    //    }
    //}
    //public DateTime DtEndOfReriod
    //{
    //    get 
    //    {
    //        DateTime res;
    //        if (DateTime.TryParse(txtDtStart.Text, out res))
    //            return res;
    //        else
    //            return DateTime.Now;
    //    }
    //    set 
    //    {
    //        txtDtStart.Text  =value .ToShortDateString ();
    //    }
    //}

    public Ecopsy.Tools.DateTimeTools.TimePeriod DetailsPeriod
    {
        get
        {
            switch (cmbPeriodType.SelectedValue)
            {
                case "1":
                    return DateTimeTools.TimePeriod.Day;
                case "2":
                    return DateTimeTools.TimePeriod.Week;
                case "3":
                    return DateTimeTools.TimePeriod.Month;
            }
            return DateTimeTools.TimePeriod.Month;
        }
        set
        {
            switch (value)
            {
                case DateTimeTools.TimePeriod.Day:
                    for (int i = 0; i < cmbPeriodType.Items.Count; i++) cmbPeriodType.Items[i].Selected = (i == 0);
                    break;
                case DateTimeTools.TimePeriod.Week:
                    for (int i = 0; i < cmbPeriodType.Items.Count; i++) cmbPeriodType.Items[i].Selected = (i == 1);
                    break;
                case DateTimeTools.TimePeriod.Month:
                    for (int i = 0; i < cmbPeriodType.Items.Count; i++) cmbPeriodType.Items[i].Selected = (i == 2);
                    break;
            }
        }
    }

#endregion

    protected void Page_Load(object sender, EventArgs e)
    {   
            InitControls();
    }

    #region Список

    public void InitControls()
    {
        ctlFilterBar1.OnFindClik = ctlFilterBar1_OnFindClik;
        ctlFilterBar1.OnFilterListClik = ctlFilterBar1_OnFilterListClik;
        ctlFilterBar1.OnFilterSaveClik = ctlFilterBar1_OnFilterSaveClik;
        ctlFilterBar1.HintServiceMethod = "GetTaskListParams";

        cmbPeriodType.Attributes.Add("onchange", "OnPeriodChange()");
        txtDtStart.Attributes.Add("onchange", "OnPeriodChange()");
        txtDtEnd.Attributes.Add("onchange", "OnPeriodChange()");
        string[] l = new string[] { cmbPeriodType.ClientID, txtDtStart.ClientID, txtDtEnd.ClientID, (Contract==null?string .Empty:Contract .ID) };
        string script = string.Format(" var PeriodType_ID='{0}';  var DtStart_ID='{1}'; var DtEnd_ID='{2}';  var ContractID ='{3}'", l);

        ScriptManager.RegisterClientScriptBlock(this, GetType(), Guid.NewGuid().ToString(), script, true);
    }
    
    [DefaultValue(false)]
    public bool EnabeBind {get;set;}

    protected override void OnDataBinding(EventArgs e)
    {
        if(EnabeBind)
                MyDataBind();
    }

    private bool ctlFilterBar1_OnFilterSaveClik()
    {
        //ModalPopupext_FilterSave.Show();
        return true;
    }



    private bool ctlFilterBar1_OnFilterListClik()
    {
        // ctlFilterList1.MyDataBind();
        // ModalPopupext_FilterList.Show();
        return true;
    }

    

    Func<string, DateTime> GetDate = delegate(string val)
    {
        DateTime s;
        if (DateTime.TryParse(val, out s))
            return s;
        else
            return DateTime.Now;

    };
   
    
    



    protected  bool ctlFilterBar1_OnFindClik(string sFindStr)
    {      
        MyDataBind();
        return true;
    }

    protected  ListWhere Where
    {
        get
        {
            string key = "Where" + KeyPref;
            if (!CacheTools.IsSessionCacheObject(key))
            {
                ListWhere r = new ListWhere();
                r.ListLoadStatment = new SideListWithContracts.SqlLoadStatment();
                r.SortCondition.SortDirection = SortDirection.Ascending;
                r.SortCondition.SortField = "FullGID";
                CacheTools.SetSessionCacheObject(key, r);
            }
           ListWhere res =  (ListWhere)CacheTools.GetSessionCacheObect(key);
            (res.ListLoadStatment as SideListWithContracts.SqlLoadStatment).DtStart = DtStart;
            (res.ListLoadStatment as SideListWithContracts.SqlLoadStatment).DtFinish = DtEnd;
            (res.ListLoadStatment as SideListWithContracts.SqlLoadStatment).Serch_Q_TypeSet = Q_TypeSet;
            if (chSelected.Checked && (null != Contract))
                (res.ListLoadStatment as SideListWithContracts.SqlLoadStatment).FilterList = Contract.ContractSurfaceItemList.GetSideIDList();
            else
                (res.ListLoadStatment as SideListWithContracts.SqlLoadStatment).FilterList.Clear();


            res.ListLoadStatment.Lexeme = ctlFilterBar1.Lexeme;
            return res;
        }
        set
        {

            string key = "Where" + KeyPref;
            CacheTools.SetSessionCacheObject(key, value);

        }

    }

    public void MyDataBind()
    {

        ObjectDS_PF ODS = new ObjectDS_PF(GetList);
        lvSides.DataSource = ODS.ImAsObjectDataSource;
        lvSides.DataBind();
        pnlHead.DataBind();

    }

    



    grdSideWitchShedule[] rs = null;
    protected grdSideWitchShedule[] GetList(int startRowIndex, int maximumRows, out int RowCount)
    {


        if (rs != null)
        {
            RowCount = rs.Length;
            return rs;
        }


        wsConstractions ws = (wsConstractions)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Constraction];
        SideListWithContracts.SideContractItemBox[] r = ws.GetSideListWithContracts((SideListWithContracts.SqlLoadStatment)Where.ListLoadStatment);

        RowCount = r.Length;
        rs = new grdSideWitchShedule[r.Length];
        int j = 0;
        foreach (SideListWithContracts.SideContractItemBox i in r)
        {
            rs[j] = new grdSideWitchShedule(i);
            j++;
        }
        RowCount = rs.Length;

        ////////заряжаем comparer функцией сортировки         
        Where.SortCondition.fnOrderBy = SortFunctions.fOrderBy;
        Array.Sort(rs, Where.SortCondition);
        return rs;
    }

    protected ListWhere GetWhere()
    {
        return Where;
    }


    /// <summary>
    /// Вернуть из контракта список периодов принадлежащих стороне 
    /// </summary>
    /// <param name="SideID"></param>
    /// <returns></returns>
    protected List<ContractSurfaceItem> GetContractSurfaceItem(string SideID)
    {
        List<ContractSurfaceItem> res = new List<ContractSurfaceItem>();
        foreach (ContractSurfaceItem i in Contract.ContractSurfaceItemList)
        {
            if (i.SideID == SideID)
                res.Add(i);
        }
        return res;
    }

    #endregion
        

    


   

    protected string GetHtmlRow(string SideID, SideShedule Shedule)
    {
        ContractSurfaceItemList l = null;

        if (null != Contract)
            l = Contract.ContractSurfaceItemList;

        return SurfaceSheduleRowWriter.GetHtml(DetailsPeriod, Shedule, l);


    }

    protected string GetHtmlHeadRow()
    {
        SideShedule sh = new SideShedule() { dtStart = DtStart, dtEnd = DtEnd };
       return SurfaceSheduleRowWriter.GetHeadRow (DetailsPeriod,sh);


    }
}
